package com.example.baseapp.service.impl;

import com.example.baseapp.entity.User;
import com.example.baseapp.repository.UserRepository;
import com.example.baseapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public User login(String openid, String nickname, String avatar, Integer gender) {
        User user = userRepository.findByOpenid(openid);
        if (user == null) {
            // 新用户注册
            user = new User();
            user.setOpenid(openid);
            user.setNickname(nickname);
            user.setAvatar(avatar);
            user.setGender(gender);
            user.setStatus(1);
            user.setCreateTime(LocalDateTime.now());
        } else {
            // 更新用户信息
            if (nickname != null) user.setNickname(nickname);
            if (avatar != null) user.setAvatar(avatar);
            if (gender != null) user.setGender(gender);
        }
        user.setUpdateTime(LocalDateTime.now());
        return userRepository.save(user);
    }

    @Override
    public User updateUser(Long userId, String nickname, String phone, String address) {
        User user = userRepository.findById(userId).orElse(null);
        if (user != null) {
            if (nickname != null) user.setNickname(nickname);
            if (phone != null) user.setPhone(phone);
            if (address != null) user.setAddress(address);
            user.setUpdateTime(LocalDateTime.now());
            return userRepository.save(user);
        }
        return null;
    }

    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public User getUserByOpenid(String openid) {
        return userRepository.findByOpenid(openid);
    }

    @Override
    public User saveOrUpdateUser(User user) {
        if (user.getId() == null) {
            user.setCreateTime(LocalDateTime.now());
        }
        user.setUpdateTime(LocalDateTime.now());
        return userRepository.save(user);
    }
} 